<script lang="ts" setup>
import {ref, reactive, watch} from 'vue';
import {useAuthStore} from "@/stores/auth";
import {
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElButton,
  ElRadio,
  ElRadioButton,
  ElRadioGroup,
  ElMessage,
} from 'element-plus';
import Editor from '@/components/WangEditor.vue'
import Upload from '@/components/Upload.vue'
import {updateConfigValueApi} from '@/api/sysConfig'

const authStore = useAuthStore();

const props = defineProps({
  formConfig: {
    type: Object,
    required: true
  }
});

// 组件类型映射表
const fieldComponents = {
  'input': ElInput,
  'select': ElSelect,
  'radio-group': ElRadioGroup,
  'radio': ElRadio,
  'radio-button': ElRadioButton,
  'date-picker': ElDatePicker,
  'textarea': ElInput,
  'editor': Editor,
  'upload': Upload,
};

// 表单数据
const formData = reactive<any>({});
// 表单验证规则
const formRules = reactive({});
// 表单引用
const formRef = ref(null);

// 初始化表单数据
const initFormData = () => {
  props.formConfig.forEach(field => {
    formData[field.key] = field.value !== undefined ? field.value : '';
  });
};

// 初始化验证规则
const initFormRules = () => {
  props.formConfig.forEach(field => {
    if (field.rules || field.required) {
      formRules[field.key] = [
        ...(field.rules || []),
        ...(field.required ? [{required: true, message: `${field.title}不能为空`, trigger: 'blur'}] : [])
      ];
    }
  });
};

// 获取组件额外属性
const getComponentProps = (field) => {
  const propsMap = {
    'date-picker': {
      type: 'date',
      format: field.format || 'YYYY-MM-DD',
      valueFormat: field.format || 'YYYY-MM-DD'
    },
    'input': {
      clearable: true,
    },
    'textarea': { // 为 textarea 设置特定属性
      type: 'textarea',
      rows: 4, // 可根据需求调整行数
      clearable: true
    },
    'editor': {  // 富文本专用配置
      height: field.height || 300,
      mode: field.mode || 'default',
      toolbarConfig: field.toolbarConfig || {},
      editorConfig: {
        placeholder: field.placeholder || '请输入内容...',
        ...field.editorConfig
      }
    },
    'upload': {
      multiple: field.multiple ?? false,
    }
  };
  return propsMap[field.type] || {};
};

// 表单提交
const submitForm = async () => {
  try {
    // 提交到后端逻辑
    await formRef.value.validate();
    await updateConfigValueApi(formData)
    if('site_title' in formData) {
      authStore.setSystem({logo: formData.logo ?? '', site_title: formData.site_title ?? ''});
    }
    ElMessage.success('更新成功');
  } catch (error) {
    console.error('验证失败:', error);
  }
};

// 监听 prop 的变化来重新初始化表单数据和规则
watch(() => props.formConfig, () => {
  initFormData();
  initFormRules();
}, {deep: true});

// 初始加载时初始化数据和规则
initFormData();
initFormRules();
</script>

<template>
  <el-form
      :model="formData"
      :rules="formRules"
      label-width="200px"
      ref="formRef"
  >
    <template v-for="field in props.formConfig" :key="field.key">
      <el-form-item
          :prop="field.key"
      >
        <template #label>
          <div class="flex items-center gap-1">
            <span>{{ field.title }}</span>
            <el-tooltip v-if="field.remark" effect="dark" :content="field.remark" placement="top">
              <el-icon>
                <component is="QuestionFilled"></component>
              </el-icon>
            </el-tooltip>
          </div>
        </template>
        <!-- 动态组件渲染 -->
        <component
            :is="fieldComponents[field.type]"
            v-model="formData[field.key]"
            v-bind="getComponentProps(field)"
        >
          <!-- 处理select等需要选项的组件 -->
          <template v-if="field.options && field.type !== 'radio-group'">
            <el-option
                v-for="opt in field.options"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
            />
          </template>
          <!-- 处理 radio 类型 -->
          <template v-if="field.type === 'radio-group'">
            <el-radio v-for="opt in field.options" :value="opt.value + ''" :key="opt.value">{{ opt.label }}</el-radio>
          </template>
        </component>
      </el-form-item>
    </template>

    <el-form-item>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </el-form-item>
  </el-form>
</template>